/*
 * @Author: hzm 
 * @Date: 2020-06-19 10:22:12 
 * @Last Modified by: hzm
 * @Last Modified time: 2020-06-19 13:58:50
 */

#include "Event.h"
#include <cassert>
#include "event2/util.h"
#include "event.h"


using namespace HeyIM;

Event:: Event(event_base* base, VoidParamHandler handler): m_base(base), m_handler(handler) {

    
}

Event::~Event() {
    assert(!m_running);
}

bool Event::start(int delay) {
    if(m_running) {
        return false;
    }

    struct timeval tv;
    struct timeval* timeoutVal;
    if(delay > 0) {
        tv.tv_sec = delay / 1000;
        tv.tv_usec = (delay % 1000) / 1000000;
        timeoutVal = &tv;
    }

    int ret = event_add(m_event, timeoutVal);
    if(ret != 0) {
        return false;
    }

    m_running = true;
    return true;
}

void Event::cancel() {
    if(!m_running) {
        return;
    }

    if(!m_event) {
        return;
    }

    event_del(m_event);
    event_free(m_event);
    m_event = nullptr;

    m_running = false;
}

bool Event::isRunning() const {
    return m_running;
}